<script setup>
import CmpEdit from '@/views/liteflow/cmp/CmpEditTabs.vue'
import CmpExec from '@/views/liteflow/cmp/CmpExec.vue'

import { reactive, ref } from 'vue'
import { VDataTableServer } from 'vuetify/labs/VDataTable'

// 组件统计
const cmpListMeta = [
  {
    icon: 'tabler-user-plus',
    color: 'error',
    title: '全部组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user-check',
    color: 'success',
    title: '动态组件',
    stats: '0',
    percentage: -0,
  },
  {
    icon: 'tabler-user-exclamation',
    color: 'warning',
    title: '脚本组件',
    stats: '0',
    percentage: +0,
  },
  {
    icon: 'tabler-user',
    color: 'primary',
    title: '其他组件',
    stats: '0',
    percentage: +0,
  },
]

// 组件分类
const open = ref([

])

const menuItems = [
  {
    title: 'Home',
    icon: 'tabler-home',
    value: 'Home',
  },
  {
    title: 'Users',
    icon: 'tabler-users',
    value: 'Users',
    children: [
      {
        title: 'Admin',
        icon: 'tabler-admin',
        value: 'Admin',
        children: [
          {
            title: 'Management',
            icon: 'tabler-users',
            value: 'Management',
            children: [
              {
                title: 'Management',
                icon: 'tabler-users',
                value: 'Management',
              },
              {
                title: 'Settings',
                icon: 'tabler-settings',
                value: 'Settings',
              },
            ],
          },
          {
            title: 'Settings',
            icon: 'tabler-settings',
            value: 'Settings',
          },
        ],
      },
      {
        title: 'Actions',
        icon: 'tabler-actions',
        value: 'Actions',
        children: [
          {
            title: 'Action1',
            icon: 'tabler-action1',
            value: 'Action1',
          },
          {
            title: 'Action2',
            icon: 'tabler-action2',
            value: 'Action2',
          },
        ],
      },
    ],
  },
]

//查询条件
const componentId = ref()
const componentName = ref()
const type = ref()

// 组件类型-下拉选择框
const nodeTypeList = reactive([])

const nodeTypeSelect = async () => {
  const res = await $ivyApi.post(API_URLS.lfCmpTypeOptions, { })

  nodeTypeList.push(...res.data)
}

// 表头
const headers = [
  {
    title: '组件ID',
    key: 'componentId',
  },
  {
    title: '组件名称',
    key: 'componentName',
  },
  {
    title: '组件类型',
    key: 'type',
  },
  {
    title: 'Java类',
    key: 'clazz',
  },
  {
    title: 'EL表达式',
    key: 'el',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

// 分页查询
const totalPage = ref(1) //总页数
const totalRows = ref(0) //总记录数
const list = ref([]) // 当前分页数据
const loadings = ref(false)

const fetchList = async msg => {
  loadings.value = true

  const res = await $ivyApi.post(API_URLS.lfCmpPage, {
    type: type.value,
    componentName: componentName.value,
    componentId: componentId.value,
    options: options.value,
  })
  
  const data = res.data

  list.value = data.list
  totalPage.value = data.totalPage
  totalRows.value = data.totalRow
  options.value.page = data.page
  loadings.value = false

  if(typeof msg === 'string'){
    res.message = msg
    showMsg(res)
  }
}

watchEffect(fetchList)

// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

// 删除操作
const deleteId = ref('')
const deleteVisible = ref(false)

const deleteOper = id => {
  deleteVisible.value = true
  deleteId.value = id
}

const deleteAgreeOper = async id => {
  const res = await $ivyApi.post(API_URLS.lfCmpDelete, {
    componentId: deleteId.value,
  })

  showMsg(res)
  fetchList()
  deleteVisible.value = false
  deleteId.value = ''
}

// 新增操作&编辑操作
const editKey = ref(1)
const operType = ref(0) // 操作类型：0新增，1更新
const currRow = ref({})
const addVisible = ref(false)

const addOper = () => {
  editKey.value++
  operType.value = 0
  currRow.value = {}
  addVisible.value = true
}

const addData = async data => {
  const res = await $ivyApi.post(API_URLS.lfCmpAdd, data)

  showMsg(res)
  fetchList()
}

const updateOper = row => {
  editKey.value++
  operType.value = 1
  currRow.value = row
  addVisible.value = true
}

const updateData = async data => {
  const res = await $ivyApi.post(API_URLS.lfCmpUpdate, data)

  showMsg(res)
  fetchList()
}

// 执行EL表达式
const execVisible = ref(false)
const execResult = ref('')
const execStatus = ref(200)

const execCmp = async cmp => {
  execVisible.value = true
  currRow.value = cmp
  
  // const res = await $ivyApi.post(API_URLS.lfCmpExec,{
  //   id: cmp.id,
  // })


  

  // execVisible.value = true
  // if(200 == res.code){
  //   execStatus.value = 200
  //   execResult.value = res.data
  // }else{
  //   execStatus.value = 500
  //   execResult.value = res.message
  // }
}

// 回调信息
const snackbar = reactive(API_URLS.resultMsg)

const showMsg = res => {
  $resultMsg.show(res, snackbar)
}

// 初始化
onMounted(() => {
  nodeTypeSelect()
})
</script>

<template>
  <section>
    <VSnackbar
      v-model="snackbar.msgVisible"
      location="top"
      :color="snackbar.msgColor"
    >
      {{ snackbar.msgContent }}
    </VSnackbar>
    <VRow>
      <VCol
        v-for="meta in cmpListMeta"
        v-if="false"
        :key="meta.title"
        cols="10"
        sm="6"
        lg="3"
      >
        <VCard>
          <VCardText class="d-flex justify-space-between">
            <div>
              <span>{{ meta.title }}</span>
              <div class="d-flex align-center gap-2 my-1">
                <h6 class="text-h4">
                  {{ meta.stats }}
                </h6>
                <span :class="meta.percentage > 0 ? 'text-success' : 'text-error'">( {{ meta.percentage > 0 ? '+' : '' }}{{ meta.percentage }})</span>
              </div>
            </div>

            <VAvatar
              rounded
              variant="tonal"
              :color="meta.color"
              :icon="meta.icon"
            />
          </VCardText>
        </VCard>
      </VCol>

      <VCol
        v-if="false"
        cols="3"
      >
        <VList v-model:opened="open">
          <template v-for="item in menuItems">
            <VListItem
              v-if="!item.children"
              :key="item.value"
              :prepend-icon="item.icon"
              :title="item.title"
              :value="item.value"
            />
            <VListGroup
              v-else
              :key="'group-'+item.value"
              :value="item.value"
            >
              <template #activator="{ props }">
                <VListItem
                  v-bind="props"
                  :prepend-icon="item.icon"
                  :title="item.title"
                />
              </template>
              <template v-for="child in item.children">
                <VListItem
                  v-if="!child.children"
                  :key="child.value"
                  :prepend-icon="child.icon"
                  :title="child.title"
                  :value="child.value"
                />
                <VListGroup
                  v-else
                  :key="'child-'+child.value"
                  :value="child.value"
                >
                  <template #activator="{ props }">
                    <VListItem
                      v-bind="props"
                      :prepend-icon="child.icon"
                      :title="child.title"
                    />
                  </template>
                  <VListItem
                    v-for="grandchild in child.children"
                    :key="'grandchild-'+grandchild.value"
                    :prepend-icon="grandchild.icon"
                    :title="grandchild.title"
                    :value="grandchild.value"
                  />
                </VListGroup>
              </template>
            </VListGroup>
          </template>
        </VList>
      </VCol>

      <VCol cols="12">
        <VCard>
          <!-- 👉 Filters -->
          <VCardText>
            <VRow>
              <!-- 👉 Select Role -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentId"
                  label="组件ID"
                  clearable
                />
              </VCol>
              <!-- 👉 Select Plan -->
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="componentName"
                  label="组件名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="4"
              >
                <VSelect
                  v-model="type"
                  label="组件类型"
                  :items="nodeTypeList"
                  clearable
                  clear-icon="tabler-x"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="inline-size: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                :loading="loadings"
                :disabled="loadings"
                size="38"
                @click="fetchList('刷新成功')"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
              >
                新增组件
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <!-- SECTION datatable -->
          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <!-- Plan -->
            <template #item.componentId="{ item }">
              <span class="font-weight-medium">{{ item.componentId }}</span>
            </template>

            <template #item.componentName="{ item }">
              <span class="font-weight-medium">{{ item.componentName }}</span>
            </template>

            <template #item.type="{ item }">
              <span class="font-weight-medium"><VChip
                label
                color="success"
                size="small"
              >  {{ item.type }} </VChip></span>
            </template>

            <template #item.clazz="{ item }">
              <span class="font-weight-medium">{{ item.clazz }}</span>
            </template>

            <template #item.el="{ item }">
              <VBtn
                variant="plain"
                size="small"
                style="padding-inline-start: 0;"
              >
                查看EL表达式
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  {{ item.el }}
                </VTooltip>
              </VBtn>
            </template>

            <!-- Actions -->
            <template #item.actions="{ item }">
              <IconBtn @click="deleteOper(item.componentId)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>

              <IconBtn @click="execCmp(item)">
                <VIcon icon="tabler-player-play-filled" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  调试
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <!-- 👉 新增组件 -->
        
        <CmpEdit
          :key="'cmp-edit-'+editKey"
          v-model:isDrawerOpen="addVisible"
          :oper-type="operType"
          :curr-row="currRow"
          @add-data="addData"
          @update-data="updateData"
        /> 
       
        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="300"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否删除组件[{{ deleteId }}]？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeOper">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <VSnackbar
          v-if="false"
          v-model="execVisible"
          multi-line
        >
          <span v-if="execStatus == 200">执行成功：</span>
          <span v-if="execStatus != 200">执行失败：</span>
          <br>
          {{ execResult }}
          <template #actions>
            <VBtn
              color="error"
              @click="execVisible = false"
            >
              关闭
            </VBtn>
          </template>
        </VSnackbar>

        <VDialog
          v-model="execVisible"
          scrollable
          width="80%"
          class="ivy-sql-build-dialog"
        >
          <DialogCloseBtn @click="execVisible = !execVisible" />
        
          <VCard>
            <VCardItem class="pb-5">
              <VCardTitle>调试</VCardTitle>
            </VCardItem>
            <VDivider />
            <VCardText>
              <CmpExec :curr-row="currRow" />
            </VCardText>
          </VCard>
        </VDialog>
      </vcol>
    </vrow>
  </section>
</template>



<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
